<template>
  <t-drawer
    :visible="internalVisible"
    :header="isEdit ? '编辑菜单' : '新增菜单'"
    size="600px"
    placement="right"
    :confirm-btn="{ content: '保存', loading: saveLoading }"
    @confirm="handleSave"
    @close="handleClose"
  >
    <t-form
      ref="menuForm"
      :data="formData"
      :rules="formRules"
      label-align="left"
      label-width="100px"
    >
      <t-form-item label="菜单类型" name="type">
        <t-select
          v-model="formData.type"
          placeholder="请选择菜单类型"
          :popup-props="{ attach: 'body' }"
        >
          <t-option :value="0" label="目录" />
          <t-option :value="1" label="菜单" />
          <t-option :value="2" label="权限" />
        </t-select>
      </t-form-item>

      <t-form-item label="菜单名称" name="name">
        <t-input v-model="formData.name" placeholder="请输入菜单名称" maxlength="50" />
      </t-form-item>

      <t-form-item label="菜单图标" name="icon" v-if="formData.type !== 2">
				<t-icon v-if="formData.icon" :name="formData.icon" :style="{ marginRight: '8px' }" />
        <t-select
          v-model="formData.icon"
          placeholder="请选择图标"
          clearable
          filterable
          :popup-props="{ attach: 'body', overlayStyle: { display: 'inline-block'}, overlayInnerStyle: {width: '400px', fontSize: '20px !important'} }"
        >
          <t-option v-for="item in iconOptions" :value="item.stem" :key="item.stem" class="icon-option">
            <t-icon :name="item.stem" />
          </t-option>
        </t-select>
      </t-form-item>

      <t-form-item label="上级菜单" name="parentId">
        <t-select
          v-model="formData.parentId"
          placeholder="请选择上级菜单（不选择为根菜单）"
          clearable
          :popup-props="{ attach: 'body' }"
        >
          <t-option
            v-for="menu in flatMenuOptions"
            :key="menu.id"
            :value="menu.id"
            :label="menu.label"
            :disabled="currentEditData && menu.id === currentEditData.id"
          >
            {{ menu.label }}
          </t-option>
        </t-select>
      </t-form-item>

      <t-form-item label="路由地址" name="path" v-if="formData.type !== 2">
        <t-input
          v-model="formData.path"
          placeholder="请输入路由地址，如：/system/menus"
          maxlength="200"
        />
      </t-form-item>

      <t-form-item label="组件路径" name="component" v-if="formData.type !== 2">
        <t-input
          v-model="formData.component"
          placeholder="请输入组件路径，如：@/views/system/menus/index.vue"
          maxlength="200"
        />
      </t-form-item>

      <t-form-item label="权限标识" name="permission" v-if="formData.type === 2">
        <t-input
          v-model="formData.permission"
          placeholder="请输入权限标识，如：system:menu:view"
          maxlength="100"
        />
      </t-form-item>

      <t-form-item label="页面缓存" name="keepAlive" v-if="formData.type === 1">
        <t-select
          v-model="formData.keepAlive"
          placeholder="请选择是否开启页面缓存"
          :popup-props="{ attach: 'body' }"
        >
          <t-option :value="1" label="开启" />
          <t-option :value="0" label="关闭" />
        </t-select>
      </t-form-item>

      <t-form-item label="排序号" name="orderNo">
        <t-input-number v-model="formData.orderNo" placeholder="请输入排序号" :min="0" :max="9999" />
      </t-form-item>

      <t-form-item label="状态" name="status">
        <t-select
          v-model="formData.status"
          placeholder="请选择状态"
          :popup-props="{ attach: 'body' }"
        >
          <t-option :value="1" label="启用" />
          <t-option :value="0" label="禁用" />
        </t-select>
      </t-form-item>
    </t-form>
  </t-drawer>
</template>

<script>
import {
  Drawer as TDrawer,
  Form as TForm,
  FormItem as TFormItem,
  Select as TSelect,
  Option as TOption,
  Input as TInput,
  InputNumber as TInputNumber,
  Icon as TIcon
} from 'tdesign-vue';
import { manifest } from 'tdesign-icons-vue';

export default {
  name: 'MenuFormDrawer',
  components: {
    TDrawer,
    TForm,
    TFormItem,
    TSelect,
    TOption,
    TInput,
    TInputNumber,
    TIcon
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    currentEditData: {
      type: Object,
      default: null
    },
    flatMenuOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      saveLoading: false,

      // 图标选项
      iconOptions: manifest,

      // 表单数据
      formData: {
        type: 0,
        name: '',
        parentId: null,
        path: '',
        component: '',
        permission: '',
        icon: '',
        isExt: false,
        show: 1,
        keepAlive: 1,
        orderNo: 0,
        status: 1,
      },

      // 表单验证规则
      formRules: {
        type: [
          { required: true, message: '请选择菜单类型', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' },
          { min: 2, message: '菜单名称至少2个字符', trigger: 'blur' },
          { max: 50, message: '菜单名称不能超过50个字符', trigger: 'blur' },
        ],
        path: [
          { max: 200, message: '路由地址不能超过200个字符', trigger: 'blur' },
        ],
        component: [
          { max: 200, message: '组件路径不能超过200个字符', trigger: 'blur' },
        ],
        permission: [
          { max: 100, message: '权限标识不能超过100个字符', trigger: 'blur' },
        ],
        orderNo: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { type: 'number', min: 0, max: 9999, message: '排序号必须在0-9999之间', trigger: 'blur' },
        ],
        keepAlive: [
          { required: true, message: '请选择是否开启页面缓存', trigger: 'change' },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' },
        ],
      },
    };
  },

  computed: {
    internalVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    }
  },

  watch: {
    visible(val) {
      if (val) {
        this.initFormData();
      }
    }
  },

  beforeDestroy() {
    // 清理资源
    this.saveLoading = false;
  },

  methods: {
    // 初始化表单数据
    initFormData() {
      if (this.isEdit && this.currentEditData) {
        const finalType = this.currentEditData.type !== undefined ? this.currentEditData.type : this.getTypeFromMenuType(this.currentEditData.menuType);

        // 编辑模式，从现有数据映射
        this.formData = {
          type: finalType,
          name: this.currentEditData.nodeName || this.currentEditData.name || '',
          parentId: this.currentEditData.parentId || null,
          path: this.currentEditData.routePath || this.currentEditData.path || this.currentEditData.route || '',
          component: this.currentEditData.component || this.currentEditData.filePath || '',
          permission: this.currentEditData.permission || '',
          icon: this.currentEditData.icon || '',
          isExt: this.currentEditData.isExt !== undefined ? this.currentEditData.isExt : false,
          show: this.currentEditData.show !== undefined ? this.currentEditData.show : 1,
          keepAlive: this.currentEditData.keepAlive !== undefined ? this.currentEditData.keepAlive : 1,
          orderNo: this.currentEditData.orderNo || this.currentEditData.sortOrder || this.currentEditData.sort || 0,
          status: this.currentEditData.status !== undefined ? this.currentEditData.status : 1,
        };

        // 确保数据响应式更新
        this.$nextTick(() => {
          console.log('表单数据设置完成:', this.formData);
        });
      } else {
        // 新增模式，使用默认值
        this.formData = {
          type: 0,
          name: '',
          parentId: null,
          path: '',
          component: '',
          permission: '',
          icon: '',
          isExt: false,
          show: 1,
          keepAlive: 1,
          orderNo: 0,
          status: 1,
        };
      }
    },

    // 将前端的menuType转换为服务端的type
    getTypeFromMenuType(menuType) {
      // 前端: 1-目录, 2-菜单, 3-权限
      // 服务端: 0-目录, 1-菜单, 2-权限
      if (menuType === undefined || menuType === null) return 1; // 默认为菜单
      if (menuType === 1) return 0; // 目录
      if (menuType === 2) return 1; // 菜单
      if (menuType === 3) return 2; // 权限
      return 1; // 默认为菜单
    },

    // 保存菜单
    async handleSave() {
      try {
        // 表单验证
        const valid = await this.$refs.menuForm.validate();
        if (!valid) return;

        this.saveLoading = true;

        // 发送保存事件给父组件
        this.$emit('save', this.formData);
      } catch (error) {
        console.error('保存菜单失败:', error);
      } finally {
        this.saveLoading = false;
      }
    },

    // 关闭抽屉
    handleClose() {
      // 通过computed属性的setter来更新visible状态
      this.internalVisible = false;
      this.$emit('close');
      // 清除表单验证状态 - 添加更安全的检查
      if (this.$refs && this.$refs.menuForm) {
        this.$refs.menuForm.clearValidate();
      }
      // 重置表单数据
      this.resetFormData();
    },

    // 设置保存状态
    setSaveLoading(loading) {
      this.saveLoading = loading;
    },

    // 重置表单数据
    resetFormData() {
      this.formData = {
        type: 0,
        name: '',
        parentId: null,
        path: '',
        component: '',
        permission: '',
        icon: '',
        isExt: false,
        show: 1,
        keepAlive: 1,
        orderNo: 0,
        status: 1,
      };
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .t-drawer__body {
  padding: 24px;
}

/deep/ .t-form-item {
  margin-bottom: 24px;
}

// 确保抽屉内的下拉菜单有正确的z-index
/deep/ .t-select__popup {
  z-index: 10000 !important;
}

/deep/ .t-popup {
  z-index: 10000 !important;
}

// 确保选择框的样式正确
/deep/ .t-select {
  width: 100%;
}
</style>